package com.qinggeng.project.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.framework.config.thread.ThreadPoolExecutorUtil;
import com.qinggeng.project.api.dto.GoodsGiftDto;
import com.qinggeng.project.system.domain.GiftProbability;
import com.qinggeng.project.system.domain.Goods;
import com.qinggeng.project.system.domain.GoodsGift;
import com.qinggeng.project.system.domain.UserWishGift;
import com.qinggeng.project.system.domain.json.GiftConfig;
import com.qinggeng.project.system.domain.json.GoodsGiftId;
import com.qinggeng.project.system.mapper.GoodsGiftMapper;
import com.qinggeng.project.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

import static com.qinggeng.project.system.domain.GoodsGift.*;

/**
 * 商品赠品Service业务层处理
 *
 * @author qinggeng
 * @date 2020-07-16
 */
@Slf4j
@Service
public class GoodsGiftServiceImpl implements IGoodsGiftService
{

    @Resource
    private GoodsGiftMapper goodsGiftMapper;
    @Autowired
    private IOrdersGoodsService ordersGoodsService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IGoodsGiftService goodsGiftService;
    @Autowired
    private IGiftProbabilityService probabilityService;
    @Autowired
    private IOrdersService ordersService;


    /**
     * 查询商品赠品
     *
     * @param giftId 商品赠品ID
     * @return 商品赠品
     */
    @Override
    public GoodsGift selectGoodsGiftById(Long giftId)
    {
        return goodsGiftMapper.selectGoodsGiftById(giftId);
    }

    @Override
    public List<GoodsGift> selectGoodsGiftList(UserWishGift userWishGift) {

        if(null==userWishGift){
            throw new CustomException("用户心愿清单不存在");
        }
        //抽奖次数
        Integer drawTimes=userWishGift.getDrawTimes();
        if(drawTimes<1) {
            return Lists.newArrayList();
        }
        GoodsGift goodsGift=null;
        String configKey="";
        //普通抽奖
        if(userWishGift.getDrawType()==0) {
            try {
                String[] ids = userWishGift.getGiftId().split(",");
                goodsGift = selectGoodsGiftById(Long.parseLong(ids[drawTimes % ids.length]));
                configKey = GOODS_GIFT_CONFIG_KEY;
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        //免单抽奖
        if(userWishGift.getDrawType()==1) {
            if (!userWishGift.getGiftId().equals(getGoodsGiftId().getFreeGiftId().toString())) {
               return Lists.newArrayList();
            }
            goodsGift = selectGoodsGiftById(getGoodsGiftId().getFreeGiftId());
            configKey = FREE_GIFT_CONFIG_KEY;
        }

        if(null==goodsGift) {
            return Lists.newArrayList();
        }

        GiftConfig giftConfig=goodsGiftService.getGiftConfig(configKey);
        //如果是根据利润率计算中奖率
        if(giftConfig.isByProfit()){
            goodsGift.setProbability(getProbabilityByProfitRate(userWishGift.getOrdersId(),giftConfig));
        }
        return addGoodsGiftList(goodsGift,giftConfig.getOtherGiftId());
    }

    public List<GoodsGift> addGoodsGiftList(GoodsGift goodsGift,Long otherGiftId){
        List<GoodsGift> goodsGiftList= Lists.newArrayList();
        goodsGiftList.add(goodsGift);

        //添加其他（未中奖）展示奖品
        GoodsGift otherGift=goodsGiftMapper.selectGoodsGiftById(otherGiftId);
        if(otherGift!=null){
            otherGift.setProbability(new BigDecimal(1).subtract(goodsGift.getProbability()));
            goodsGiftList.add(otherGift);
        }
        return goodsGiftList;
    }

    /**
     * 查询商品赠品列表
     *
     * @param goodsGift 商品赠品
     * @return 商品赠品
     */
    @Override
    public List<GoodsGift> selectGoodsGiftList(GoodsGift goodsGift)
    {
        return goodsGiftMapper.selectGoodsGiftList(goodsGift);
    }

    @Override
    public List<GoodsGiftDto> selectGoodsGiftDtoList(GoodsGift goodsGift)
    {
        return goodsGiftMapper.selectGoodsGiftDtoList(goodsGift.getShopId(),goodsGift.getGiftType());
    }

    /**
     * 新增商品赠品
     *
     * @param goodsGift 商品赠品
     * @return 结果
     */
    @Override
    public int insertGoodsGift(GoodsGift goodsGift){
        return goodsGiftMapper.insertGoodsGift(goodsGift);
    }

    /**
     * 修改商品赠品
     *
     * @param goodsGift 商品赠品
     * @return 结果
     */
    @Override
    public int updateGoodsGift(GoodsGift goodsGift)
    {
        return goodsGiftMapper.updateGoodsGift(goodsGift);
    }

    /**
     * 批量删除商品赠品
     *
     * @param giftIds 需要删除的商品赠品ID
     * @return 结果
     */
    @Override
    public int deleteGoodsGiftByIds(Long[] giftIds)
    {
        return goodsGiftMapper.deleteGoodsGiftByIds(giftIds);
    }

    /**
     * 删除商品赠品信息
     *
     * @param giftId 商品赠品ID
     * @return 结果
     */
    @Override
    public int deleteGoodsGiftById(Long giftId)
    {
        return goodsGiftMapper.deleteGoodsGiftById(giftId);
    }

    @Override
    public List<GoodsGift> selectGoodsGiftList(Double groupPrice) {

        //商品价格=拼团价格
        BigDecimal goodsPrice=new BigDecimal(groupPrice.toString());

        List<GiftProbability> probabilityList=probabilityService.selectGiftProbabilityList(null);

        for (GiftProbability probability:probabilityList ) {

            if(null==probability.getMinPrice()){
                continue;
            }
            if(goodsPrice.compareTo(probability.getMinPrice())<0){
                continue;
            }
            boolean hasMax=probability.getMaxPrice()!=null;
            if(hasMax&&goodsPrice.compareTo(probability.getMaxPrice())>=0){
                continue;
            }
            return getGoodsGiftList(probability);
        }
        return Lists.newArrayList();
    }

    /**
     * 获取奖品，设置中奖率
     * @param
     * @param
     * @return
     */
    private List<GoodsGift> getGoodsGiftList(GiftProbability  gp){

        GoodsGiftId ids=goodsGiftService.getGoodsGiftId();

        List<GoodsGift> list=Lists.newArrayList();

        list=addGoodsGiftList(list,ids.getFreeGiftId(),gp.getFreeProbability());

        list=addGoodsGiftList(list,ids.getHalfGiftId(),gp.getHalfProbability());

        list=addGoodsGiftList(list,ids.getOtherGiftId(),gp.getOtherProbability());

        return list;
    }

    private List<GoodsGift> addGoodsGiftList(List<GoodsGift> goodsGiftList,Long giftId,BigDecimal probability){
        GoodsGift goodsGift=goodsGiftService.selectGoodsGiftById(giftId);
        if(goodsGift!=null){
            goodsGift.setProbability(probability);
            goodsGiftList.add(goodsGift);
        }
        return goodsGiftList;
    }

    /**
     * 获取奖品ID
     * @return
     */
    public GoodsGiftId getGoodsGiftId(){
        String goodsGiftIdJson=sysConfigService.selectConfigByKey(GOODS_GIFT_ID_KEY).toString();
        return JSON.parseObject(goodsGiftIdJson,GoodsGiftId.class);
    }

    @Override
    public Long getLoseGiftId() {
        return this.getGoodsGiftId().getLoseGiftId();
    }

    @Override
    public Long getFreeGiftId() {
        return this.getGoodsGiftId().getFreeGiftId();
    }

    @Override
    public Long getHalfGiftId() {
        return this.getGoodsGiftId().getHalfGiftId();
    }

    @Override
    public Long getOtherGiftId() {
        return this.getGoodsGiftId().getOtherGiftId();
    }

    @Override
    public GiftConfig getGiftConfig(String configKey){
        //礼物配置文件
        String giftConfigJson=sysConfigService.selectConfigByKey(configKey).toString();
        try{
            return JSON.parseObject(giftConfigJson,GiftConfig.class);
        }catch (Exception e){
            return null;
        }
    }

    public Long getOtherGiftId(String configKey) {
        GiftConfig giftConfig=this.getGiftConfig(configKey);
        if(null==giftConfig||null==giftConfig.getOtherGiftId()){
            return null;
        }
        return giftConfig.getOtherGiftId();
    }


    @Override
    public int updateGoodsGiftNum(GoodsGift goodsGift) {
        int rows=0;
        try{
            rows=goodsGiftMapper.updateGoodsGiftNum(goodsGift);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return rows;
    }

    @Override
    public boolean checkGoodsGiftNum(Long giftId) {
        return goodsGiftMapper.checkGoodsGiftNum(giftId);
    }

    /**
     * 根据订单平均利润率计算中奖率
     * @param ordersId
     * @param
     * @return
     */
    private BigDecimal getProbabilityByProfitRate(Long ordersId,GiftConfig giftConfig){
        if(null==giftConfig||null==giftConfig.getDrawModulus()||null==giftConfig.getMaxProbability()){
            log.error("读取giftConfig配置文件错误");
            throw new CustomException("读取giftConfig配置文件错误");
        }
        //订单平均利润率
        BigDecimal profitRate=ordersGoodsService.getOrdersAverageProfitRateByOrdersId(ordersId);
        if(profitRate.compareTo(new BigDecimal(0))<0){
            profitRate=new BigDecimal(0);
        }
        //设置中奖率
        BigDecimal probability=profitRate.multiply(giftConfig.getDrawModulus());
        if(probability.compareTo(giftConfig.getMaxProbability())>0){
            probability=giftConfig.getMaxProbability();
        }
        return probability;
    }


    @Override
    public GoodsGift getGoodsGiftIdByRandom(Long[] giftIds){

        Long giftId= giftIds[(int)(Math.random()*giftIds.length)];
        GoodsGift goodsGift=goodsGiftMapper.selectGoodsGiftById(giftId);
        if(null==goodsGift){
            log.error("goodsGift is null,giftId="+giftId);
            return null;
        }
        if(null==goodsGift.getGiftNum()||goodsGift.getGiftNum().compareTo(1L)<0){
           log.error("礼品库存不足，giftId="+giftId);
           return null;
        }
        return goodsGift;
    }
}
